package com.todo.partner.application.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.todo.common.common.entity.response.BizResponse;
import com.todo.common.common.entity.response.page.PageResult;
import com.todo.common.common.enums.BizErrorCodeEnum;
import com.todo.common.common.exception.BizException;
import com.todo.content.api.request.*;
import com.todo.content.api.response.ContentDetailResponse;
import com.todo.content.api.response.ContentInfoResponse;
import com.todo.partner.application.convert.PartnerConvert;
import com.todo.partner.application.entity.bo.PartnerContentDetailBO;
import com.todo.partner.application.entity.condition.ContentPartnerConditionBO;
import com.todo.partner.application.remote.ContentInfoRemote;
import com.todo.partner.application.service.PartnerContentService;
import com.todo.partner.infrastructure.entity.condition.ContentPartnerCondition;
import com.todo.partner.infrastructure.entity.po.ContentPartnerPO;
import com.todo.partner.infrastructure.repository.ContentPartnerRepository;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * (ContentPartner)表服务实现类
 *
 * @author zhangwenxiang
 * @since 2024-03-04 00:19:46
 */
@Slf4j
@Service("contentPartnerService")
public class PartnerContentServiceImpl implements PartnerContentService {

    @Resource
    private ContentPartnerRepository contentPartnerRepository;
    @Resource
    private ContentInfoRemote contentInfoRemote;

    @Override
    @Transactional
    public Boolean insertContentPartner(PartnerContentDetailBO partnerContentDetailBO) {
        if (partnerContentDetailBO == null || partnerContentDetailBO.getPartnerInfoBO() == null || partnerContentDetailBO.getPartnerContentBO() == null) {
            throw new BizException(BizErrorCodeEnum.PARAM_ERROR);
        }
        //保存内容前置校验
        SavePreCheckRequest savePreCheckRequest = PartnerConvert.convertToSavePreCheckRequest(partnerContentDetailBO, true);
        BizResponse<Boolean> checkResult = contentInfoRemote.savePreCheck(savePreCheckRequest);
        if (checkResult == null || !checkResult.isSuccess() || !checkResult.getData()) {
            log.warn("ContentPartnerService#insertContentPartner 新增搭子内容失败，内容信息保存校验失败 request：【{}】", JSONObject.toJSONString(savePreCheckRequest));
            return false;
        }
        //实际内容保存动作
        InsertContentDetailRequest insertContentDetailRequest = PartnerConvert.convertToInsertContentDetailRequest(partnerContentDetailBO);
        BizResponse<Long> insertResult = contentInfoRemote.insertContentDetail(insertContentDetailRequest);
        if (insertResult == null || !insertResult.isSuccess() || insertResult.getData() == null) {
            log.warn("ContentPartnerService#insertContentPartner 新增搭子内容失败，内容信息保存失败 request：【{}】", JSONObject.toJSONString(insertContentDetailRequest));
            return false;
        }
        Long contentId = insertResult.getData();
        partnerContentDetailBO.getPartnerContentBO().setContentId(contentId);
        ContentPartnerPO contentPartnerPO = PartnerConvert.convertToContentPartnerPO(partnerContentDetailBO);
        contentPartnerPO.setContentId(contentId);
        Boolean saveResult = contentPartnerRepository.insertContentPartner(contentPartnerPO);
        if (!saveResult) {
            log.warn("ContentPartnerService#insertContentPartner 新增搭子内容失败，搭子信息保存失败 partnerContentDetailBO：【{}】", JSONObject.toJSONString(partnerContentDetailBO));
            throw new BizException(BizErrorCodeEnum.OPERATION_FAILED);
        }
        return saveResult;
    }

    @Override
    @Transactional
    public Boolean updateContentPartner(PartnerContentDetailBO partnerContentDetailBO) {
        if (partnerContentDetailBO == null || partnerContentDetailBO.getPartnerInfoBO() == null || partnerContentDetailBO.getPartnerContentBO() == null) {
            throw new BizException(BizErrorCodeEnum.PARAM_ERROR);
        }

        PartnerContentDetailBO alreadyDetailBO = queryContentPartner(partnerContentDetailBO.getPartnerInfoBO().getId());
        if (alreadyDetailBO == null) {
            throw new BizException(BizErrorCodeEnum.DATA_NOT_EXIST);
        }

        //保存内容前置校验
        SavePreCheckRequest savePreCheckRequest = PartnerConvert.convertToSavePreCheckRequest(partnerContentDetailBO, false);
        BizResponse<Boolean> savePreCheck = contentInfoRemote.savePreCheck(savePreCheckRequest);
        if (savePreCheck == null || !savePreCheck.isSuccess() || !savePreCheck.getData()) {
            log.warn("ContentPartnerService#updateContentPartner 更新搭子内容失败，内容信息保存校验失败 savePreCheckRequest：【{}】", JSONObject.toJSONString(savePreCheckRequest));
            return false;
        }
        UpdateContentDetailRequest request = PartnerConvert.convertToUpdateContentDetailRequest(partnerContentDetailBO);
        BizResponse<Boolean> updateResult = contentInfoRemote.updateContentDetail(request);
        if (updateResult == null || !updateResult.isSuccess() || !updateResult.getData()) {
            log.warn("ContentPartnerService#updateContentPartner 更新搭子内容失败，内容信息保存失败 partnerContentDetailBO：【{}】", JSONObject.toJSONString(partnerContentDetailBO));
            return false;
        }
        ContentPartnerPO contentPartnerPO = PartnerConvert.convertToContentPartnerPO(partnerContentDetailBO);
        Boolean updated = contentPartnerRepository.updateContentPartnerById(contentPartnerPO);
        if (!updated) {
            log.warn("ContentPartnerService#updateContentPartner 更新搭子内容失败，搭子信息保存失败 partnerContentDetailBO：【{}】", JSONObject.toJSONString(partnerContentDetailBO));
            throw new BizException(BizErrorCodeEnum.OPERATION_FAILED);
        }

        return updated;
    }

    @Override
    @Transactional
    public Boolean removeContentPartner(Long id) {
        if (id == null || id < 0) {
            throw new BizException(BizErrorCodeEnum.PARAM_ERROR);
        }
        PartnerContentDetailBO partnerContentDetailBO = queryContentPartner(id);
        if (partnerContentDetailBO == null) {
            log.info("ContentPartnerService#removeContentPartner 删除搭子内容完成 ，根据主键查询数据为空，默认删除成功 id：【{}】", id);
            return true;
        }
        Boolean removeResult = contentPartnerRepository.removeContentPartnerById(id);
        if (!removeResult) {
            log.warn("ContentPartnerService#removeContentPartner 删除搭子内容失败，搭子信息删除失败 id：【{}】", id);
            return false;
        }
        RemoveContentDetailByIdRequest request = new RemoveContentDetailByIdRequest();
        request.setContentId(id);
        BizResponse<Boolean> contentResult = contentInfoRemote.removeContentDetailById(request);
        if (contentResult == null || !contentResult.isSuccess() || !contentResult.getData()) {
            log.warn("ContentPartnerService#removeContentPartner 删除搭子内容失败，内容信息删除失败 contentId：【{}】", partnerContentDetailBO.getPartnerContentBO().getContentId());
            throw new BizException(BizErrorCodeEnum.OPERATION_FAILED);
        }
        return contentResult.getData();
    }

    @Override
    public PartnerContentDetailBO queryContentPartner(Long id) {
        if (id == null || id < 0) {
            return null;
        }
        ContentPartnerPO contentPartnerPO = contentPartnerRepository.queryContentPartnerPOById(id);
        if (contentPartnerPO == null) {
            log.info("ContentPartnerService#queryContentPartner 根据主键查询数据为空，返回空 id：【{}】", id);
            return null;
        }
        QueryContentDetailByIdRequest request = new QueryContentDetailByIdRequest();
        request.setContentId(contentPartnerPO.getContentId());
        BizResponse<ContentDetailResponse> bizResponse = contentInfoRemote.queryContentDetailById(request);
        if (bizResponse == null || !bizResponse.isSuccess() || bizResponse.getData() == null) {
            log.info("ContentPartnerService#queryContentPartner 根据内容id查询数据为空，返回空 contentId：【{}】", contentPartnerPO.getContentId());
            return null;
        }
        return PartnerConvert.buildPartnerContentDetailBO(bizResponse.getData(), contentPartnerPO);
    }

    @Override
    public List<PartnerContentDetailBO> queryContentPartnerList(List<Long> idList) {
        if (CollectionUtils.isEmpty(idList)) {
            return Collections.emptyList();
        }
        List<ContentPartnerPO> contentPartnerPOList = contentPartnerRepository.queryContentPartnerList(idList);
        if (CollectionUtils.isEmpty(contentPartnerPOList)) {
            log.warn("ContentPartnerService#queryContentPartnerList 根据主键查询数据为空，返回空 idList：【{}】", JSONObject.toJSONString(idList));
            return Collections.emptyList();
        }
        List<Long> contentIdList = contentPartnerPOList.stream().map(ContentPartnerPO::getContentId).collect(Collectors.toList());
        QueryContentInfoByIdListRequest request = new QueryContentInfoByIdListRequest();
        request.setContentIdList(contentIdList);
        BizResponse<List<ContentInfoResponse>> listBizResponse = contentInfoRemote.queryContentInfoByIdList(request);
        if (listBizResponse == null || !listBizResponse.isSuccess() || CollectionUtils.isEmpty(listBizResponse.getData())) {
            log.warn("ContentPartnerService#queryContentPartnerList 根据内容id查询数据为空，返回空 contentIdList：【{}】", JSONObject.toJSONString(contentIdList));
            return Collections.emptyList();
        }
        Map<Long, ContentInfoResponse> contentInfoBOMap = listBizResponse.getData().stream().collect(Collectors.toMap(ContentInfoResponse::getContentId, Function.identity()));
        List<PartnerContentDetailBO> result = new ArrayList<>();
        for (ContentPartnerPO contentPartnerPO : contentPartnerPOList) {
            if (contentInfoBOMap.containsKey(contentPartnerPO.getContentId())) {
                PartnerContentDetailBO partnerContentDetailBO = PartnerConvert.buildPartnerContentDetailBO(contentInfoBOMap.get(contentPartnerPO.getContentId()), contentPartnerPO);
                result.add(partnerContentDetailBO);
            }
        }
        return result;
    }

    @Override
    public PartnerContentDetailBO queryContentPartnerByContentId(Long contentId) {
        if (contentId == null || contentId < 0) {
            return null;
        }
        ContentPartnerPO contentPartnerPO = contentPartnerRepository.queryContentPartnerPOByContentId(contentId);
        if (contentPartnerPO == null) {
            log.info("ContentPartnerService#queryContentPartnerByContentId 根据内容id查询数据为空，返回空 contentId：【{}】", contentId);
            return null;
        }
        QueryContentDetailByIdRequest request = new QueryContentDetailByIdRequest();
        request.setContentId(contentPartnerPO.getContentId());
        BizResponse<ContentDetailResponse> bizResponse = contentInfoRemote.queryContentDetailById(request);
        if (bizResponse == null || !bizResponse.isSuccess() || bizResponse.getData() == null) {
            log.info("ContentPartnerService#queryContentPartnerByContentId 根据内容id查询数据为空，返回空 contentId：【{}】", contentPartnerPO.getContentId());
            return null;
        }
        return PartnerConvert.buildPartnerContentDetailBO(bizResponse.getData(), contentPartnerPO);
    }

    @Override
    public PageResult<PartnerContentDetailBO> queryContentPartnerByCondition(ContentPartnerConditionBO conditionBO) {
        if (conditionBO == null) {
            return new PageResult<>();
        }
        ContentPartnerCondition condition = PartnerConvert.convertToContentPartnerCondition(conditionBO);
        PageResult<ContentPartnerPO> pageResult = contentPartnerRepository.queryContentPartnerByCondition(condition);
        if (pageResult == null) {
            return new PageResult<>();
        }
        PageResult<PartnerContentDetailBO> result = new PageResult<>();
        result.setPageSize(pageResult.getPageSize());
        result.setTotal(pageResult.getTotal());
        result.setCurrentIndex(pageResult.getCurrentIndex());
        result.setPageNum(pageResult.getPageNum());
        result.setHasNext(pageResult.isHasNext());

        if (CollectionUtils.isEmpty(pageResult.getResults())) {
            return result;
        }
        List<Long> contentIdList = pageResult.getResults().stream().map(ContentPartnerPO::getContentId).collect(Collectors.toList());
        QueryContentInfoByIdListRequest request = new QueryContentInfoByIdListRequest();
        request.setContentIdList(contentIdList);
        BizResponse<List<ContentInfoResponse>> listBizResponse = contentInfoRemote.queryContentInfoByIdList(request);
        if (listBizResponse == null || !listBizResponse.isSuccess() || CollectionUtils.isEmpty(listBizResponse.getData())) {
            log.warn("ContentPartnerService#queryContentPartnerByCondition 根据内容idList查询数据为空，返回空 contentIdList：【{}】", JSONObject.toJSONString(contentIdList));
            return new PageResult<>();
        }
        Map<Long, ContentInfoResponse> contentInfoBOMap = listBizResponse.getData().stream().collect(Collectors.toMap(ContentInfoResponse::getContentId, Function.identity()));
        List<PartnerContentDetailBO> partnerContentDetailBOList = new ArrayList<>();
        for (ContentPartnerPO contentPartnerPO : pageResult.getResults()) {
            ContentInfoResponse contentInfoResponse = contentInfoBOMap.get(contentPartnerPO.getContentId());
            if (contentInfoResponse == null) {
                continue;
            }
            PartnerContentDetailBO partnerContentDetailBO = PartnerConvert.buildPartnerContentDetailBO(contentInfoResponse, contentPartnerPO);
            partnerContentDetailBOList.add(partnerContentDetailBO);
        }
        result.setResults(partnerContentDetailBOList);
        return result;
    }
}
